package com.offcn.seckill.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.PageResult;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;

import com.offcn.seckill.entity.SeckillStatus;
import com.offcn.seckill.pojo.SeckillOrder;
import com.offcn.seckill.service.SeckillOrderService;
import com.offcn.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/****
 * @Author:ujiuye
 * @Description:
 * @Date 2021/2/1 14:19
 *****/

@RestController
@RequestMapping("/seckillOrder")
@CrossOrigin
public class SeckillOrderController {

    @Autowired
    private SeckillOrderService seckillOrderService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${mq.exchange}")
    private String exchange;

    @Value("${mq.routingKey}")
    private String routingKey;


    @RequestMapping("/query")
    public Result queryOrderStatus(){
        // 获取令牌并解析用户名
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String token = details.getTokenValue();
        String username = TokenDecode.getUsername(token);
        SeckillStatus seckillStatus = seckillOrderService.queryStatus(username);
        if (seckillStatus != null) {
            String seckillOrderJSON = (String) stringRedisTemplate.boundHashOps("seckillOrder").get(username);
            return new Result(true,StatusCode.OK,seckillStatus,"查询成功");
        }
        return new Result(false,StatusCode.ERROR,"查询失败");

    }

    @RequestMapping("/add")
    public Result add(String time, String id) {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String token = details.getTokenValue();
        String username = TokenDecode.getUsername(token);
        try {
            Boolean boo = seckillOrderService.add(id, time, username);
            if (boo) {
                /**
                 * 	"out_trade_no":"12313412351271",
                 * 	"total_amount":"10.05",
                 * 	"username": "xiaobai",
                 * 	"exchange":"com.seckill.pay",
                 * 	"routingKey": "seckill"
                 */

                return new Result(true,StatusCode.OK,"抢单成功");
            }else{
                return new Result(false,StatusCode.ERROR,"抢单失败");
            }
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,e.getMessage());
        }
    }


}
